package com.pccw.ssh.daoImp;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.pccw.ssh.dao.StockDao;
import com.pccw.ssh.domain.Stock;

public class StockDaoImp extends HibernateDaoSupport implements StockDao {
	
	private Log log = LogFactory.getLog(this.getClass());

	public void add(Stock stock) {
		this.getHibernateTemplate().save(stock);
	}

	public void delete(Stock stock) {
		this.getHibernateTemplate().delete(stock);
	}

	@SuppressWarnings("unchecked")
	public Stock getByPK(String num) {
		List<Stock> stocks = this.getHibernateTemplate().find("from Stock s where s.num="+num);
		return stocks.get(0);
	}

	public void update(Stock Stock) {
		this.getHibernateTemplate().update(Stock);
	}

	@SuppressWarnings("unchecked")
	public List<Stock> getByAttribute(final String attributeName,
			final String attributeValue) {
		
		HibernateTemplate ht = new HibernateTemplate(this.getSessionFactory());
		List<Stock> results = (List<Stock>) ht.execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException{
				Query query = session.createQuery("from Stock s where s."+attributeName+"="+"\'"+attributeValue+"\'");
				return query.list();
			}
		});
		
		return results;
	}

	@SuppressWarnings("unchecked")
	public List<Stock> getByPO(Stock stock) {
		
		final StringBuilder queryStr = new StringBuilder(" from Stock s ");
		boolean isFirst = true;
		
		if(null != stock.getNum()&&!"".equals(stock.getNum())){
			queryStr.append((isFirst? " where ":" and ")+" s.num = " +"\'"+ stock.getNum()+"\'");
			isFirst = false;
		}
		if(null != stock.getName()&&!"".equals(stock.getName())){
			queryStr.append((isFirst? " where ":" and ")+" s.name = " +"\'"+ stock.getName()+"\'");
			isFirst = false;
		}
		if(null != stock.getPrice()&&!"".equals(stock.getPrice())){
			queryStr.append((isFirst? " where ":" and ")+" s.price = " +"\'"+ stock.getPrice()+"\'");
			isFirst = false;
		}
		log.info(queryStr.toString());
		HibernateTemplate ht = new HibernateTemplate(this.getSessionFactory());
		List<Stock> results = (List<Stock>) ht.execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException{
				Query query = session.createQuery(queryStr.toString());
				return query.list();
			}
		});
		
		return results;
	}

}
